package com.winit.openapi.util;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;

public class RequestUtil {
	
	/****** get requestMsg ******/
	public static RequestMsg getRequestMsg(ServletRequest request){
		return (RequestMsg) request.getAttribute(ApiConstant.REQUEST_MSG);
	}
	/****** set requestMsg ******/
	public static void setRequestMsg(ServletRequest request,RequestMsg requestMsg){
		request.setAttribute(ApiConstant.REQUEST_MSG, requestMsg);
	}
	/****** get responseMsg ******/
	public static ResponseMsg getResponseMsg(ServletRequest request){
		return (ResponseMsg) request.getAttribute(ApiConstant.RESPONSE_MSG);
	}
	/****** set responseMsg ******/
	public static void setResponseMsg(ServletRequest request,ResponseMsg responseMsg){
		request.setAttribute(ApiConstant.RESPONSE_MSG, responseMsg);
	}
	
	/****** get user ******/
	/*public static User getUser(ServletRequest request){
		return (User) request.getAttribute(ApiConstant.API_USER);
	}*/
	/****** set user ******/
	/*public static void setUser(ServletRequest request,User user){
		request.setAttribute(ApiConstant.API_USER, user);
	}*/
	
	/**
	 * 获取请求真实ip信息 (考虑经过交换机和ngix等的ip可能会变更)
	 * 
	 * @param request
	 * @return
	 */
	public static String getIp(HttpServletRequest request)
	{
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
		{
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
		{
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
		{
			ip = request.getHeader("X-Cluster-Client-Ip");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
		{
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}
